﻿using System;
using System.IO.Ports;
using System.Threading.Tasks;
using NModbus.IO;

public class SerialPortResource : IStreamResource
{
    private readonly SerialPort _serialPort;

    public SerialPortResource(SerialPort serialPort)
    {
        _serialPort = serialPort ?? throw new ArgumentNullException(nameof(serialPort));
    }

    public int InfiniteTimeout => -1;

    public int ReadTimeout
    {
        get => _serialPort.ReadTimeout;
        set => _serialPort.ReadTimeout = value;
    }

    public int WriteTimeout
    {
        get => _serialPort.WriteTimeout;
        set => _serialPort.WriteTimeout = value;
    }

    public int Read(byte[] buffer, int offset, int count) => _serialPort.Read(buffer, offset, count);

    public Task<int> ReadAsync(byte[] buffer, int offset, int count) => Task.FromResult(Read(buffer, offset, count));

    public void Write(byte[] buffer, int offset, int count) => _serialPort.Write(buffer, offset, count);

    public Task WriteAsync(byte[] buffer, int offset, int count)
    {
        Write(buffer, offset, count);
        return Task.CompletedTask;
    }

    public void DiscardInBuffer() => _serialPort.DiscardInBuffer();

    public void DiscardOutBuffer() => _serialPort.DiscardOutBuffer();

    public void Dispose() => _serialPort?.Dispose();
}
